package kr.co.mustgo.controller.membership;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import kr.co.mustgo.domain.membership.Membership;
import kr.co.mustgo.model.service.membership.MembershipService;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.SessionScope;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/membership/") //class에 지정한 URL - 모든 Handler 메소드들의 URL 앞에 붙이는 공통 경로 지정
public class MembershipController {

	@Autowired
	private MembershipService service;


	
	/***************가입처리***************/
	//가입 폼
	@RequestMapping(value="join.do", method=RequestMethod.GET)
	public String joinForm(){
		return "tiles/membership/join_form.jsp";
	}
	
	/*아이디 중복 체크*/
	@RequestMapping(value = "membershipIdCheck.do", method = RequestMethod.POST)
	public String memberIdCheck(String id, ModelMap map) throws SQLException, IOException {
		System.out.println("id = " + id);
		Membership membership = service.getMembershipById(id);
		System.out.println(membership);
		
			map.addAttribute("membership", membership);
			
		return "jsonView";
	}
	
	//회원가입 완료
	@RequestMapping(value="join.do", method=RequestMethod.POST)
	public String joinMembership(Membership membership, HttpSession session) throws Exception{
		service.joinMembership(membership);
		session.setAttribute("login_info", membership);
		//join_success.jsp
		return "tiles/membership/join_success.jsp";
	}
	
	/***************로그인 처리***************/
	/*	@RequestMapping(value="login.do", method=RequestMethod.GET)
		public String loginForm(){
			System.out.println("asdfjl");
			return "/WEB-INF/view/membership/login_form.jsp";//View name 리턴
		}*/
	
		//로그인 form을 제공
		@RequestMapping(value="login.do", method=RequestMethod.GET)
		public ModelAndView loginForm(String result){
			
			ModelAndView mav = new ModelAndView();
			mav.setViewName("/WEB-INF/view/membership/login_form.jsp");
			mav.addObject("result", result);
			
			return mav;//View name 리턴
		}
		//로그인 처리
		@RequestMapping(value="login.do", method=RequestMethod.POST)
		public ModelAndView login(String id, String password, HttpSession session, ModelMap map) throws SQLException{
			//비지니스 로직 - Model호출(Business Service)
			
			ModelAndView mav = new ModelAndView();
			mav.setViewName("redirect:/mainpage/home.do");
			System.out.println(id);
			Membership membership = service.getMembershipById(id);
			System.out.println("기져온 값 : " + membership);
			String text = null;
			if(membership!=null){//id - ok
				if(membership.getPassword().equals(password)){
					//로그인 성공 후 세션에 로그인 확인값 올려놓기
		 			session.setAttribute("login_info", membership);
		 			System.out.println("성공");
		 			text="1";
		 			
		 		}else{//pwd 틀린경우
		 			//로그인 확인 할 세션스코프의 값 넣기
		 			System.out.println("비번실패");
		 			text="2";
		 		}
			}else{//id가 틀린경우
				System.out.println("아이디실패");
				text="2";
			}
			//로그인 성공 - session - attribute(login_info, 로그인한 회원 정보)
			//성공 : view - main.jsp
			mav.addObject("result", text);
			
			return mav;
		}
		
		/***************로그아웃 처리***************/
		@RequestMapping(value = "logout.do", method=RequestMethod.GET)
		public String logout(HttpSession session){
			//새션을 소멸 -> main.jsp
			session.invalidate(); 
			//return "/WEB-INF/view/membership/logout_success.jsp";
			//return "redirect:/index.jsp";
			return "redirect:/";
		}
		
		
		/***************마이페이지***************/
		@RequestMapping(value = "mypage.do", method=RequestMethod.GET)
		public String mypage() throws Exception{
			return "tiles/membership/mypage.jsp";
		}
		
		
		/***************내정보 수정***************/
		@RequestMapping(value = "modify.do", method=RequestMethod.GET)
		public String modify(ModelMap map, HttpSession session) throws Exception{
			
			Membership membership = (Membership)session.getAttribute("login_info");
			System.out.println(membership);
			
			String birthDate[] = membership.getBirthDate().split("-");
			map.addAttribute("year", birthDate[0]);
			map.addAttribute("month", birthDate[1]);
			map.addAttribute("day", birthDate[2]);
			
			String email[] = membership.getEmail().split("@");
			map.addAttribute("email1", email[0]);
			map.addAttribute("email2", email[1]);
			
			String homePhone[] = membership.getHomePhone().split("-");
			map.addAttribute("homePhone1", homePhone[0]);
			map.addAttribute("homePhone2", homePhone[1]);
			map.addAttribute("homePhone3", homePhone[2]);
			
			String cellPhone[] = membership.getCellPhone().split("-");
			map.addAttribute("cellPhone1", cellPhone[0]);
			map.addAttribute("cellPhone2", cellPhone[1]);
			map.addAttribute("cellPhone3", cellPhone[2]);
			
			
			String zipCode[] = membership.getZipCode().split("-");
			map.addAttribute("zipCode1", zipCode[0]);
			map.addAttribute("zipCode2", zipCode[1]);
			
			String address[] = membership.getAddress().split("/");
			map.addAttribute("addr1", address[0]);
			map.addAttribute("addr2", address[1]);
			
			return "tiles/membership/modify_form.jsp";
		}
		
		@RequestMapping(value = "modify.do", method=RequestMethod.POST)
		public String modify(Membership membership, HttpSession session) throws Exception{
			service.modifyMembership(membership);
			session.setAttribute("login_info", membership);
			System.out.println(membership);
			return "tiles/membership/update_success.jsp";
		}
		
		/***************아이디 찾기***************/
		//ID찾기 폼 
		@RequestMapping(value = "findId.do", method=RequestMethod.GET)
		public String findId(){
			return "/WEB-INF/view/membership/findId_form.jsp";
		}
		
		@RequestMapping(value = "findId.do", method=RequestMethod.POST)
		public String findId(String name, String email){
			
			return "/WEB-INF/view/membership/findId_form.jsp";
		}
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		//전체 회원 목록 조회
		@RequestMapping("membershipList.do")
		public ModelAndView membershipList() throws Exception{
			List<Membership> list =service.getMembershipList();
			return new ModelAndView("membership/membership_list.jsp", "membership_list", list);
		}
		@RequestMapping("login/getMembershipInfo.do")
		public String getMembershipInfo(HttpSession session, ModelMap map){
			String url = null;
			//로그인 체크 - o -> member_info.jsp
			//				 - X -> login_form.jsp (attribute : 메시지)
			if(session.getAttribute("login_info") != null){//로그인 한 사람
				url="/WEB-INF/view/membership/membership_info.jsp";
			}else{//로그인 안 한 사람
				map.addAttribute("error_message", "로그인을 먼저 해야합니다.");
				url="/WEB-INF/view/membership/login_form.jsp";
			}
			return url;
		}
		/**************수정처리*************/
		//수정 폼
		@RequestMapping(value="login/modify.do", method=RequestMethod.GET)
		public String modifyForm(HttpSession session, ModelMap map){
			//로그인 체크
			String url = null;
			if(session.getAttribute("login_info") != null){
				url = "/WEB-INF/view/membership/modify_form.jsp";
			}else{
				url = "membership/login_form.jsp";
				map.addAttribute("error_message","로그인이 필요합니다.");
			}
			return url;
		}
		@RequestMapping(value="login/modify.do", method=RequestMethod.POST)
		public void modifyMemberInfo(HttpSession session, @ModelAttribute Membership membership, ModelMap map) throws Exception{
			//로그인 여부 체크
			String url = null;
			Membership m= (Membership) session.getAttribute("login_form");
			if(m==null){
				url =  "/WEB-INF/view/membership/login_form.jsp";
				map.addAttribute("error_message","로그인이 필요합니다.");
			}else{
				//로그인 상태 
				//비지니스 로직 - service.modifyMember(수정할 정보)
				service.modifyMembership(membership);
				
				//Session의 회원정보 수정
				//member.setJoinDate(m.getJoinDate());
				session.setAttribute("login_info", membership);
				//응답처리 : member_info.jsp
				url = "/WEB-INF/view/membership/membership_info.jsp";
			}
			
			//return url;
		}
		//탈퇴
		@RequestMapping("login/removeMembership.do")
		public String removeMembership(HttpSession session, ModelMap map) throws SQLException{
			//로그인 확인
			String url = null;
			Membership m = (Membership) session.getAttribute("login_info");
			if(m != null){
				//회원 정보 삭제 - removeMemberById(id)
				//service.removeMemberById(m.getId());
				//로그아웃 처리
				session.invalidate(); //새션을 소멸
				//응답 : main.jsp
				url = "main.jsp";
			}else{
				url="/WEB-INF/view/membership/login_form.jsp";
				map.addAttribute("error_message", "로그인이 필요합니다.");
			}
			return url;
		}
		//전체목록 조회 - 페이징 처리
		@RequestMapping("membershipListPaging.do")
		public ModelAndView membershipListPaging(@RequestParam(defaultValue="1") int page) throws Exception{
			Map map = service.getMembershipListPaging(page);
			//membership_list_paging.jsp
			return new ModelAndView("membership/membership_list_paging.jsp", map);
		}
		
		@RequestMapping("searchForm.do")
		public String searchForm(){
			return "/WEB-INF/view/membership/ajax_search.jsp";
		}
		
		@RequestMapping("searchMembershipById.do")
		public String searchMemberById(String id, ModelMap map) throws Exception{
			Membership membership = service.getMembershipById(id);
			//map.addAttribute("member", member);//{member :{id:"id1", name:"김철수"}} -> 이렇게 만들어줌
			map.addAttribute("membership", "성공");//"성공"
			return "jsonViewLiteral"; //View Name - MappingJackson2JsonView
		}
	
}//end class
